package com.yuqing.myblogServe.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuqing.myblogServe.common.lang.Const;
import com.yuqing.myblogServe.common.lang.Result;
import com.yuqing.myblogServe.dao.entity.SysMenu;
import com.yuqing.myblogServe.dao.entity.SysRoleMenu;
import com.yuqing.myblogServe.dao.entity.SysUser;
import com.yuqing.myblogServe.service.SysMenuService;
import com.yuqing.myblogServe.service.SysRoleMenuService;
import com.yuqing.myblogServe.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yuqing
 * @since 2022-08-02
 */
@RestController
@RequestMapping("/api/sysMenu")
@Api(value = "菜单管理 controller" ,tags = {"菜单管理接口"})
public class SysMenuController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysMenuService sysMenuService;
    @Autowired
    SysRoleMenuService sysRoleMenuService;
    /**
     * 获取当前用户的菜单栏以及权限
     */
    @GetMapping("/nav")
    @ApiOperation(value = "获取当前用户的菜单栏以及权限")
    public Result nav(Principal principal) {
        String username = principal.getName();
        SysUser sysUser = sysUserService.getByUsername(username);
        // ROLE_Admin,sys:user:save
        String[] authoritys = StringUtils.tokenizeToStringArray(
                sysUserService.getUserAuthorityInfo(sysUser.getId())
                , ",");
        return Result.succ(
                MapUtil.builder()
                        .put("nav", sysMenuService.getCurrentUserNav())
                        .put("authoritys", authoritys)
                        .map()
        );
    }
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAnyAuthority('sys:menu:list')")
    @ApiOperation(value = "菜单详情")
    public Result info(@PathVariable("id") Long id) {
        return Result.succ(sysMenuService.getById(id));
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    @ApiOperation(value = "菜单列表")
    public Result list() {
        List<SysMenu> menus = sysMenuService.tree();
        return Result.succ(menus);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    @ApiOperation(value = "新增菜单")
    public Result save(@Validated @RequestBody SysMenu sysMenu) {
        sysMenu.setCreated(LocalDateTime.now());
        sysMenu.setStatu(Const.STATUS_ON);
        sysMenuService.save(sysMenu);
        return Result.succ(sysMenu);
    }
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    @ApiOperation(value = "修改菜单")
    public Result update(@Validated @RequestBody SysMenu sysMenu) {
        sysMenu.setUpdated(LocalDateTime.now());
        sysMenuService.updateById(sysMenu);
        // 清除所有与该菜单相关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(sysMenu.getId());
        return Result.succ(sysMenu);
    }
    @Transactional
    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    @ApiOperation(value = "删除菜单")
    public Result delete(@PathVariable Long id) {
        int count = (int) sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
        if (count > 0) {
            return Result.fail("请先删除子菜单");
        }

        // 先清除所有与该菜单相关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(id);
        sysMenuService.removeById(id);

        // 同步删除
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("menu_id", id));
        return Result.succ("");
    }
}

